﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;

[System.Serializable]
public class ConnectionEvent : UnityEvent<RectTransform, RectTransform> { }

public class CircleConnector : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public RectTransform linePrefab;
    public float connectionRadius = 50f;
    public ConnectionEvent onConnectionCreated;

    private RectTransform currentLine;
    private RectTransform startCircle;
    private bool isConnecting = false;

    public CircleConnector elseCircle;
    public int key = 0;
   

    void Start()
    {
        startCircle = GetComponent<RectTransform>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        if (!isConnecting)
        {
            CreateNewLine();
            UpdateLinePosition(eventData.position);
            isConnecting = true;
        }
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (isConnecting)
        {
            UpdateLinePosition(eventData.position);
        }
    }


    public bool Check()
    {
        if (elseCircle == null)
        {
            GetComponent<Image>().color = Color.red;
            return false;
        }
        if (key != elseCircle.key)
        {
            if (currentLine)
            {
                currentLine.GetComponent<Image>().color = Color.red;
                GetComponent<Image>().color = Color.red;
                return false;
            }
        }
        else
        {
            if (currentLine)
            {
                currentLine.GetComponent<Image>().color = Color.green;
                GetComponent<Image>().color = Color.green;
                elseCircle.GetComponent<Image>().color = Color.green;
            }
           
        }
        return true;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (!isConnecting) return;

        GameObject target = eventData.pointerCurrentRaycast.gameObject;
        if (target != null && target != gameObject&&target.CompareTag("LX") )
        {
            RectTransform endCircle = target.GetComponent<RectTransform>();
            FinalizeConnection(endCircle);
            onConnectionCreated?.Invoke(startCircle, endCircle);
            elseCircle = target.GetComponent<CircleConnector>();
            elseCircle.elseCircle = this;
        }
        else
        {
            Destroy(currentLine.gameObject);
        }

        isConnecting = false;
    }

    private void CreateNewLine()
    {
        if (currentLine != null) Destroy(currentLine.gameObject); 
        currentLine = Instantiate(linePrefab, transform.parent);
        currentLine.transform.SetAsFirstSibling();
    }

    private void UpdateLinePosition(Vector2 screenPos)
    {
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            transform.parent as RectTransform,
            screenPos,
            null,
            out Vector2 localPoint);

        Vector2 startPos = GetEdgePosition(startCircle, localPoint);
        Vector2 endPos = localPoint;

        UpdateLineRenderer(startPos, endPos);
    }

    private void FinalizeConnection(RectTransform endCircle)
    {
        Vector2 startEdge = GetEdgePosition(startCircle, endCircle.anchoredPosition);
        Vector2 endEdge = GetEdgePosition(endCircle, startCircle.anchoredPosition);

        UpdateLineRenderer(startEdge, endEdge);
       // currentLine.GetComponent<ConnectionLine>().Initialize(startCircle, endCircle);
    }

    private Vector2 GetEdgePosition(RectTransform circle, Vector2 targetPos)
    {
        Vector2 direction = (targetPos - circle.anchoredPosition).normalized;
        return circle.anchoredPosition + direction * (circle.rect.width / 2f);
    }

    private void UpdateLineRenderer(Vector2 start, Vector2 end)
    {
        RectTransform lineRect = currentLine.GetComponent<RectTransform>();
        lineRect.anchoredPosition = (start + end) / 2f;
        lineRect.sizeDelta = new Vector2(Vector2.Distance(start, end), lineRect.sizeDelta.y);

        Vector2 direction = (end - start).normalized;
        lineRect.localEulerAngles = new Vector3(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
    }
}

